package com.example.hotel.controller;

import com.example.hotel.entity.Equip;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.example.hotel.common.JsonResult;
import com.example.hotel.entity.Item;
import com.example.hotel.service.ItemService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "物品管理")
@RestController
@CrossOrigin
@RequestMapping("item")
public class ItemController {

    @Autowired
    ItemService service;

    @ApiOperation(value = "获取库存中所有物品的信息")
    @GetMapping("findAll")
    public JsonResult<List<Item>> findAll() {
        List<Item> list = service.findAll();
        if (!(list.isEmpty())) {
            return JsonResult.ok(list);
        } else {
            return JsonResult.fail(5001, "所有物品查询失败");
        }
    }

    @ApiOperation(value = "添加新物品")
    @GetMapping("insert")
    public JsonResult insert(Item item) {
        try {
            int r = service.insert(item);
            if (r > 0) {
                return JsonResult.ok();
            } else {
                return JsonResult.fail(5001, "物品添加失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail();
        }
    }

    @ApiOperation(value = "删除物品")
    @GetMapping("delete")
    public JsonResult delete(int item_id) {
        try {
            int r = service.deleteById(item_id);
            if (r > 0) {
                return JsonResult.ok();
            } else {
                return JsonResult.fail(5001, "物品删除失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail();
        }
    }

    @ApiOperation(value = "更新物品信息")
    @GetMapping("update")
    public JsonResult updateEquip(@Param("itemId") Integer itemId, @Param("name") String name, @Param("type") String type,
                                  @Param("num") Integer num, @Param("vacantNum") Integer vacantNum) {
        try {
            Item item = new Item();
            item.setItemId(itemId);
            item.setName(name);
            item.setType(type);
            item.setNum(num);
            item.setVacantNum(vacantNum);

            int r = service.update(item);
            if (r > 0) {
                return JsonResult.ok();
            } else {
                return JsonResult.fail(5001, "物品更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail();
        }
    }

}
